package com
{
	import flash.display.Sprite;
	
	import flash.external.ExternalInterface;
	
	/**
	 *
	 *
	   var a:String = Cookies.getCookie("uid");
	   if (!a) {
	   a = "" + uint(Math.random() * 1000000) + new Date().time;
	   Cookies.setCookie("uid", a);
	   }
	 * ...
	 * @author db0@qq.com
	 */
	public class Cookies extends Sprite
	{
		
		public function Cookies()
		{
			//new logs();
			//addChild(logs.txt);
			//embedJS();
			//var a:String = getCookie("username");
			//deleteCookie("username");
			//logs.adds("get username:", a);
			//if (!a)
			//{
			//a = "" + new Date();
			//logs.adds(a);
			//setCookie("username", a);
			//}
		}
		
		public static function toLogin(str:String = null):void
		{
			if (ExternalInterface.available)
				try
				{
					logs.adds('isReady ?');
					ExternalInterface.call('isReady');
				}
				catch (error:SecurityError)
				{
					logs.adds("log A SecurityError occurred: " + error.message);
				}
				catch (error2:Error)
				{
					logs.adds("log An Error occurred: " + error2.message);
				}
		}
		
		/**
		 * 绑定js
		 */
		public static function embedJS(str:String = null):void
		{
			if (str == null)
			{
				str = "";
				//设置cookie
				str += 'function setCookie_(name, value, expires, security) {  var str = name + "=" + escape(value);      if (expires != null) str += ";expires=" + new Date(expires).toGMTString() + ""; if (security == true) str += ";secure";document.cookie = str;}';
				//获取cookie       
				str += 'function getCookie_(name) { var arr = document.cookie.match(new RegExp(";?" +name + "=([^;]*)")); if(arr != null) return unescape(arr[1]);return null;}';
				str += 'function deleteCookie_(name) { var d = new Date(); d.setTime(d.getTime() - 1);  var value = getCookie_(name);if(value != null) {alert(document.cookie);document.cookie = name + "=" + escape(value) + ";expire=" + d.toGMTString(); }}';
			}
			if (ExternalInterface.available)
			{
				ExternalInterface.call("eval", str);
			}
		}
		
		/**
		 * 设置cookie
		 *
		 * @param name      cookie名称
		 * @param value                        cookie值
		 * @param expires                cookie过期时间
		 * @param security                是否加密
		 *
		 */
		public static function setCookie(name:String, value:String, expiresate:Object = null, security:Boolean = false):void
		{
			if (ExternalInterface.available)
			{
				ExternalInterface.call("setCookie_", name, value, expiresate ? expiresate.time : expiresate, security);
			}
		}
		
		/**
		 * 获取cookie值
		 *
		 * @param name
		 * @return
		 *
		 */
		public static function getCookie(name:String):String
		{
			if (ExternalInterface.available)
			{
				return ExternalInterface.call("getCookie_", name);
			}
			
			return null;
		}
		
		/**
		 * 删除cookie
		 *
		 * @param name
		 *
		 */
		public static function deleteCookie(name:String):void
		{
			if (ExternalInterface.available)
			{
				ExternalInterface.call("deleteCookie_", name);
			}
		}
	}
}
